package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**处理与指定客户端的HTTP交互
 * HTTP
 *
 */

public class ClientHandler implements Runnable {
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {

            //1 解析请求
                //1.1解析请求行
                String method=""; //请求方式
                String uri=""; //抽象路径
                String protocol="";//协议版本

        try {
            InputStream in = socket.getInputStream();
            StringBuilder builder = new StringBuilder();
            int d ;
            //pre保存上次读取到的字符，cur保存本次读取到的字符
            char pre = 'a',cur='a';
            while ((d=in.read())!=-1){
                cur =(char)d; //本次读取到的字符
                if (pre==13&&cur==10){ //是否连续读到了回车+换行
                    break;
                }
                builder.append(cur);
                pre = cur;
            }
            String line = builder.toString().trim();
            System.out.println(line);

            /*StringBuilder builder1 =new StringBuilder();
            char b;
            for (int i=0;i<line.length();i++){
                b=line.charAt(i);
                line.substring(i);
                if (b=='/'){
                    break;
                }
                method+=b;
            }
            for (int i=0;i<line.length();i++){
                b=line.charAt(i);
                line.substring(i);
                if (b=='/'){
                    break;
                }
                uri+=b;


            }*/

            //将请求行为内容解析并复制给相应的methid，uri，protocl
            String[] data =line.split("\\s");
            method =data[0];
            uri = data[1];
            protocol = data[2];


            /*
                    如果浏览器发送空请求。重启浏览器或者清空内存
             */
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);

                //1.2解析消息头
                //1.3解析消息正文
            //2 处理请求

            //2 放送响应
        }catch (IOException e){
            e.printStackTrace();
        }finally {
           try {
               //交互完后与客户端连接
               socket.close();
           }catch (IOException e){
               e.printStackTrace();
           }
        }

    }
}
